package com.example.computer_exam_training_sys.mapper;

import com.example.computer_exam_training_sys.entity.UserWrongQuestionsInfo;
import com.example.computer_exam_training_sys.vo.QuestionWithPoint;
import com.example.computer_exam_training_sys.vo.UserWrongQuestionWithCourseVO;
import org.apache.ibatis.annotations.*;
import java.util.List;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface UserWrongQuestionsMapper {
    // 查全部
    @Select("SELECT * FROM user_wrong_questions WHERE is_deleted = 0")
    List<UserWrongQuestionsInfo> findAll();

    // 查单用户所有错题
    @Select("SELECT * FROM user_wrong_questions WHERE user_id = #{userId} AND is_deleted = 0")
    List<UserWrongQuestionsInfo> findByUserId(Integer userId);

    // 按照 question_id 查找错题
    @Select("SELECT * FROM user_wrong_questions WHERE question_id = #{questionId} AND is_deleted = 0")
    List<UserWrongQuestionsInfo> findByQuestionId(Integer questionId);

    // 插入错题记录
    @Insert("INSERT INTO user_wrong_questions " +
            "(user_id, question_id, course_id, point_id, source_type, source_id, wrong_count, last_wrong_time, is_mastered, is_deleted, updated_at) " +
            "VALUES (#{userId}, #{questionId}, #{courseId}, #{pointId}, #{sourceType}, #{sourceId}, 1, #{lastWrongTime}, #{isMastered}, #{isDeleted}, NOW()) " +
            "ON DUPLICATE KEY UPDATE " +
            "wrong_count = wrong_count + 1, " +
            "last_wrong_time = #{lastWrongTime}, " +
            "course_id = VALUES(course_id), " +
            "point_id = VALUES(point_id), " +
            "updated_at = NOW(), " +
            "is_deleted = 0")
    int insertOrUpdate(UserWrongQuestionsInfo info);

    // 更新错题信息
    @Update("UPDATE user_wrong_questions SET " +
            "wrong_count = #{wrongCount}, " +
            "is_mastered = #{isMastered}, " +
            "last_wrong_time = #{lastWrongTime}, " +
            "course_id = #{courseId}, " +
            "point_id = #{pointId}, " +
            "updated_at = NOW() " +
            "WHERE id = #{id}")
    int update(UserWrongQuestionsInfo info);

    // 标记删除（逻辑删除）
    @Update("UPDATE user_wrong_questions SET is_deleted = 1, updated_at = NOW() WHERE id = #{id}")
    int softDelete(Integer id);

    // 彻底删除
    @Delete("DELETE FROM user_wrong_questions WHERE id = #{id}")
    int hardDelete(Integer id);


    // 联表查询：根据point_id查题目及知识点信息
    @Select("SELECT q.*, k.point_name, k.course_id " +
            "FROM questions q " +
            "LEFT JOIN knowledge_points k ON q.point_id = k.point_id " +
            "WHERE q.point_id = #{pointId}")
    List<QuestionWithPoint> selectQuestionsWithPointByPointId(@Param("pointId") Integer pointId);


    // 通过课程ID查找该课程下所有错题（含知识点、题目内容）
    @Select("SELECT uwq.id, uwq.user_id, uwq.question_id, uwq.course_id, c.course_name, uwq.point_id, kp.point_name, " +
            "uwq.wrong_count, uwq.last_wrong_time, uwq.is_mastered, q.content AS question_content, q.analysis ,q.answer" +
            "FROM user_wrong_questions uwq " +
            "LEFT JOIN courses c ON uwq.course_id = c.course_id " +
            "LEFT JOIN knowledge_points kp ON uwq.point_id = kp.point_id " +
            "LEFT JOIN questions q ON uwq.question_id = q.question_id " +
            "WHERE uwq.is_deleted = 0 AND uwq.course_id = #{courseId}")
    List<UserWrongQuestionWithCourseVO> findWrongQuestionsByCourseId(@Param("courseId") Integer courseId);

    //多条件查询
    @Select({
            "<script>",
            "SELECT uwq.id, uwq.user_id, uwq.question_id, uwq.course_id, c.course_name,",
            "       uwq.point_id, kp.point_name, uwq.wrong_count, uwq.last_wrong_time,",
            "       uwq.is_mastered, q.content AS question_content, uwq.source_type, uwq.created_at,q.answer",
            "FROM user_wrong_questions uwq",
            "LEFT JOIN courses c ON uwq.course_id = c.course_id",
            "LEFT JOIN knowledge_points kp ON uwq.point_id = kp.point_id",
            "LEFT JOIN questions q ON uwq.question_id = q.question_id",
            "WHERE uwq.is_deleted = 0",
            "<if test='userId != null'> AND uwq.user_id = #{userId} </if>",  // 添加用户ID条件
            "<if test='courseId != null'> AND uwq.course_id = #{courseId} </if>",
            "<if test='pointId != null'> AND uwq.point_id = #{pointId} </if>",
            "<if test='isMastered != null'> AND uwq.is_mastered = #{isMastered} </if>",
            "<if test='sourceType != null'> AND uwq.source_type = #{sourceType} </if>",
            "<if test='startTime != null and endTime != null'>",
            "  AND uwq.created_at BETWEEN #{startTime} AND #{endTime}",
            "</if>",
            "ORDER BY uwq.last_wrong_time DESC",
            "LIMIT #{offset}, #{size}",
            "</script>"
    })
    List<UserWrongQuestionWithCourseVO> queryWrongQuestions(
            @Param("userId") Integer userId,  // 添加用户ID参数
            @Param("courseId") Integer courseId,
            @Param("pointId") Integer pointId,
            @Param("isMastered") Integer isMastered,
            @Param("sourceType") Integer sourceType,
            @Param("startTime") String startTime,
            @Param("endTime") String endTime,
            @Param("offset") Integer offset,
            @Param("size") Integer size
    );

    @Select({
            "<script>",
            "SELECT COUNT(*) FROM user_wrong_questions uwq",
            "WHERE uwq.is_deleted = 0",
            "<if test='userId != null'> AND uwq.user_id = #{userId} </if>", // 新增条件
            "<if test='courseId != null'> AND uwq.course_id = #{courseId} </if>",
            "<if test='pointId != null'> AND uwq.point_id = #{pointId} </if>",
            "<if test='isMastered != null'> AND uwq.is_mastered = #{isMastered} </if>",
            "<if test='sourceType != null'> AND uwq.source_type = #{sourceType} </if>",
            "<if test='startTime != null and endTime != null'>",
            "  AND uwq.created_at BETWEEN #{startTime} AND #{endTime}",
            "</if>",
            "</script>"
    })
    int countWrongQuestions(
            @Param("userId") Integer userId, // 新增参数
            @Param("courseId") Integer courseId,
            @Param("pointId") Integer pointId,
            @Param("isMastered") Integer isMastered,
            @Param("sourceType") Integer sourceType,
            @Param("startTime") String startTime,
            @Param("endTime") String endTime
    );

    @Select({
            "<script>",
            "SELECT uwq.id, uwq.user_id, uwq.question_id, uwq.course_id, c.course_name,",
            "       uwq.point_id, kp.point_name, uwq.wrong_count, uwq.last_wrong_time,",
            "       uwq.is_mastered, q.content AS question_content, q.analysis, q.answer", // 加上q.answer
            "FROM user_wrong_questions uwq",
            "LEFT JOIN courses c ON uwq.course_id = c.course_id",
            "LEFT JOIN knowledge_points kp ON uwq.point_id = kp.point_id",
            "LEFT JOIN questions q ON uwq.question_id = q.question_id",
            "WHERE uwq.is_deleted = 0 AND uwq.id IN",
            "  <foreach item='item' index='index' collection='list'",
            "           open='(' separator=',' close=')'>",
            "    #{item}",
            "  </foreach>",
            "</script>"
    })
    List<UserWrongQuestionWithCourseVO> findWrongQuestionsByIds(@Param("list") List<Integer> ids);

    // 只更新掌握状态
    @Update("UPDATE user_wrong_questions SET " +
            "is_mastered = #{isMastered}, " +
            "updated_at = NOW() " +
            "WHERE id = #{id}")
    int updateMastered(UserWrongQuestionsInfo info);
    
    // 统计用户不重复的错题数量
    @Select("SELECT COUNT(DISTINCT question_id) FROM user_wrong_questions WHERE user_id = #{userId} AND is_deleted = 0")
    int countDistinctQuestionsByUserId(@Param("userId") Integer userId);
  }
